import 'dart:async';
import 'dart:math';

import 'package:fate_blind_box/chat_view/meet_audio_player.dart';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';

import 'ahu_text.dart';

class AudioMessageView extends StatefulWidget {
  final EMMessage message;
  final EMVoiceMessageBody messageBody;
  final EMUserInfo? userInfo;

  const AudioMessageView({
    super.key,
    required this.message,
    required this.messageBody,
    this.userInfo,
  });

  @override
  State<AudioMessageView> createState() => _AudioMessageViewState();
}

class _AudioMessageViewState extends State<AudioMessageView> {
  final double minWidth = 90;
  final double maxWidths = 250;
  final double maxDuration = 60;

  // 语音是否播放中
  bool isPlaying = false;
  int aniIndex = 2;

  // 定时器
  Timer? _timer;

  final List<String> toAniList = [
    'images/sound/ic_sound_to_1.svg',
    'images/sound/ic_sound_to_2.svg',
    'images/sound/ic_sound_to_3.svg'
  ];

  final List<String> fromAniList = [
    'images/sound/ic_sound_from_1.svg',
    'images/sound/ic_sound_from_2.svg',
    'images/sound/ic_sound_from_3.svg'
  ];

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      final maxWidth = min(constraints.maxWidth, maxWidths);
      final width = minWidth +
          (maxWidth - minWidth) *
              (widget.messageBody.duration.toDouble() / maxDuration);
      bool isNotSelf = widget.message.direction == MessageDirection.RECEIVE;
      Color bgColor = isNotSelf ? Colors.white : ThemeColor.colorCF8F23;
      Color textColor = isNotSelf ? Colors.black : Colors.white;

      return GestureDetector(
          onTap: () async {
            if (isPlaying) {
              _stopAudioPlay();
            } else {
              _startAudioPlay();
            }
          },
          child: Column(
            children: [
              // isNotSelf?personWidget():const SizedBox(),
              // SizedBox(height:isNotSelf? 4.w:0),
              Container(
                width: width,
                height: 40.w,
                padding: const EdgeInsets.all(10),
                // margin: const EdgeInsets.only(top: 10, bottom: 10),
                constraints: const BoxConstraints(maxWidth: 240),
                decoration: BoxDecoration(
                    color: bgColor,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(
                            widget.message.direction == MessageDirection.RECEIVE
                                ? 0.w
                                : 16.w),
                        topRight: Radius.circular(
                            widget.message.direction == MessageDirection.SEND
                                ? 0.w
                                : 16.w),
                        bottomLeft: Radius.circular(16.w),
                        bottomRight: Radius.circular(16.w))),
                child: isNotSelf
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          SvgPicture.asset(
                            isPlaying ? fromAniList[aniIndex] : fromAniList[2],
                            width: 28,
                            height: 28,
                            color: Colors.black,
                          ),
                          Text(
                            "${widget.messageBody.duration}''",
                            style: TextStyle(color: textColor),
                          ),
                        ],
                      )
                    : Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Text(
                            "${widget.messageBody.duration}''",
                            style: TextStyle(color: textColor),
                          ),
                          // const SizedBox(
                          //   width: 8,
                          // ),
                          SvgPicture.asset(
                            isPlaying ? toAniList[aniIndex] : toAniList[2],
                            width: 28,
                            height: 28,
                            color: Colors.white,
                          )
                        ],
                      ),
              )
            ],
          ));
    });
  }

  /// 成员信息
  Widget personWidget() {
    if (widget.userInfo?.gender == 2) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 2.w),
            margin: EdgeInsets.only(right: 4.w),
            decoration: BoxDecoration(
              color: '#FFF3FD'.stringToColor,
              borderRadius: BorderRadius.circular(8.w),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(width: 6.w),
                Image.asset(
                  'images/user/txl_woman_icon.png',
                  width: 12.w,
                  height: 12.w,
                ),
                SizedBox(width: 3.w),
                AhuText(
                  text: '${widget.userInfo?.birth}',
                  fontSize: 12,
                  color: '#FE73CF'.stringToColor,
                  fontWeight: FontWeight.w400,
                ),
                SizedBox(width: 6.w),
              ],
            ),
          ),
          AhuText(
            text: '${widget.userInfo?.nickName}',
            color: '#868686'.stringToColor,
            fontSize: 11,
            fontWeight: FontWeight.w400,
          )
        ],
      );
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.symmetric(vertical: 2.w),
          margin: EdgeInsets.only(right: 4.w),
          decoration: BoxDecoration(
            color: '#F3F7FF'.stringToColor,
            borderRadius: BorderRadius.circular(8.w),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(width: 6.w),
              Image.asset(
                'images/user/txl_man_icon.png',
                width: 12.w,
                height: 12.w,
              ),
              SizedBox(width: 3.w),
              AhuText(
                text: '${widget.userInfo?.birth}',
                fontSize: 12,
                color: '#739BFE'.stringToColor,
                fontWeight: FontWeight.w400,
              ),
              SizedBox(width: 6.w),
            ],
          ),
        ),
        AhuText(
          text: '${widget.userInfo?.nickName}',
          color: '#868686'.stringToColor,
          fontSize: 11,
          fontWeight: FontWeight.w400,
        )
      ],
    );
  }

  void _startAudioPlay() {
    _timer?.cancel();
    MeetAudioPlayer.instance.startPlayer(widget.messageBody.remotePath!);
    _startPlayAni(widget.messageBody.duration);
  }

  void _startPlayAni(int duration) {
    setState(() {
      isPlaying = true;
    });
    _timer = Timer.periodic(const Duration(milliseconds: 200), (timer) {
      setState(() {
        if (aniIndex >= 2) {
          aniIndex = 0;
        } else {
          aniIndex++;
        }
      });
      if (200 * timer.tick >= duration * 1000) {
        _stopAudioPlay();
      }
    });
  }

  _stopAudioPlay() {
    MeetAudioPlayer.instance.stopPlayer();
    _stopPlayAni();
  }

  void _stopPlayAni() {
    _timer?.cancel();
    setState(() {
      isPlaying = false;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer?.cancel();
  }
}
